﻿using System;
using System.IO;
using System.Linq;

namespace Device
{
    /// <summary>
    /// BYD200烧录器
    /// </summary>
    public class BYD200
    {
        private static string _port;

        private static void ClearLogFile()
        {
            string path = Environment.CurrentDirectory + $"\\Rp{_port}t_.txt";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        /// <summary>
        /// 烧录并校验
        /// </summary>
        /// <param name="mcuType"> </param>
        /// <param name="port">    </param>
        /// <param name="hexPath"> </param>
        /// <param name="message"> </param>
        /// <returns> </returns>
        public static bool WriteHexAndCheck(string mcuType, string port, string hexPath, out string[] message)
        {
            _port = port;
            ClearLogFile();
            string path = Environment.CurrentDirectory;
            string cmd = $"{path}\\CmdLinWPxBYD.exe -Chip={mcuType} -COM={port.Substring(3)} -LoadMain={hexPath} -5V -AutoProg";
            ShellExecute.Run(cmd);

            return CheckResult(out message);
        }

        private static bool CheckResult(out string[] message)
        {
            message = null;
            string path = Environment.CurrentDirectory + $"\\Rpt_{_port}.txt";
            if (!File.Exists(path))
            {
                throw new Exception("200BYD未找到烧录日志");
            }
            string[] result = File.ReadAllLines(path);
            if (result.Any(x => x.Contains("Programming Success!")) & result.Any(x => x.Contains("Main Data verify success!")))    // 烧录成功
            {
                var tmp = result.Where(x => x.Contains("CheckSum")).ToList();
                if (tmp is not null & tmp.Count > 0)
                {
                    message = new string[tmp.Count];
                    for (int i = 0; i < tmp.Count; i++)
                    {
                        message[i] = tmp[i].Substring(tmp[i].IndexOf("Chip"));
                    }
                }

                return true;
            }
            else
                return false;
        }
    }
}